// SmarTest Studio - 项目页面JavaScript (面向对象重构版)

/**
 * ProjectPage 主类 - 管理项目页面的所有功能
 */
class ProjectPage {
    constructor() {
        // DOM元素缓存
        this.elements = {
            deviceSelect: null,
            deviceFrame: null,
            uiTree: null,
            leftPanel: null,
            rightPanel: null,
            projectContainer: null,
            aiInput: null,
            aiChat: null
        };
        
        // 设备选择器实例
        this.deviceSelector = null;
        
        // AI助手实例
        this.aiAssistant = null;
        
        // 初始化页面
        this.init();
    }
    
    /**
     * 初始化页面功能
     */
    init() {
        // 等待DOM加载完成
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => this.initializeComponents());
        } else {
            this.initializeComponents();
        }
    }
    
    /**
     * 初始化所有组件
     */
    initializeComponents() {
        // 缓存DOM元素
        this.cacheElements();
        
        // 初始化各个功能模块
        this.initPanelState();
        this.initSidebars();
        this.initEditBar();
        this.initAIAssistant();
    }
    
    /**
     * 缓存常用DOM元素
     */
    cacheElements() {
        this.elements.deviceSelect = document.querySelector('.device-select');
        this.elements.deviceFrame = document.querySelector('.device-frame');
        this.elements.uiTree = document.getElementById('ui-element-tree');
        this.elements.leftPanel = document.querySelector('.left-panel');
        this.elements.rightPanel = document.querySelector('.right-panel');
        this.elements.projectContainer = document.querySelector('.project-container');
        this.elements.aiInput = document.querySelector('.ai-input input');
        this.elements.aiChat = document.querySelector('.ai-chat');
    }
    
    /**
     * 初始化面板状态
     */
    initPanelState() {
        const { rightPanel, projectContainer } = this.elements;
        
        if (rightPanel && projectContainer) {
            if (rightPanel.classList.contains('expanded')) {
                projectContainer.classList.remove('right-collapsed');
            } else {
                projectContainer.classList.add('right-collapsed');
            }
        }
    }
    
    /**
     * 初始化编辑栏功能
     */
    initEditBar() {
        // 初始化设备选择器（编辑栏的核心功能）
        this.initDeviceSelector();
    }
    
    /**
     * 初始化设备选择器
     */
    initDeviceSelector() {
        // 创建UI查看器实例
        this.uiViewer = new UiViewer({
            container: this.elements.uiTree,
            onNodeClick: (nodeData, nodeElement) => {
                console.log('节点被点击:', nodeData);
                // 可以在这里添加节点点击的处理逻辑
            },
            onNodeHover: (nodeData, nodeElement, action) => {
                // 可以在这里添加节点悬停的处理逻辑
                if (action === 'enter') {
                    console.log('鼠标进入节点:', nodeData);
                } else {
                    console.log('鼠标离开节点:', nodeData);
                }
            },
            showNodeIds: true,
            expandByDefault: false
        });
        
        // 创建设备选择器实例
        this.deviceSelector = new DeviceSelector({
            deviceSelectElement: this.elements.deviceSelect,
            deviceFrameElement: this.elements.deviceFrame,
            uiTreeElement: this.elements.uiTree,
            uiViewer: this.uiViewer,
            onDeviceSelected: (device) => {
                console.log('设备已选择:', device);
            },
            onUiTreeUpdate: (uiTreeData) => {
                // 使用UiViewer渲染UI控件树
                if (uiTreeData) {
                    this.uiViewer.renderTree(uiTreeData);
                } else {
                    this.uiViewer.showEmpty();
                }
            },
            onError: (error) => {
                console.error('设备选择器错误:', error);
                this.uiViewer.showError(error.message || '发生未知错误');
                // 当WebRTC失败时，回退到传统截图方式
                if (this.deviceSelector.currentWebRTCClient) {
                    const deviceSn = this.deviceSelector.currentWebRTCClient.deviceSn;
                    // this.deviceSelector.fallbackToTraditionalScreenshot(deviceSn);
                }
            }
        });
        
        // 初始化UI控件树刷新按钮
        this.uiViewer.initRefreshButton(this.deviceSelector);
    }
    

    
    /**
     * 初始化侧边栏切换功能
     */
    initSidebars() {
        this.initLeftSidebar();
        this.initRightSidebar();
    }
    
    /**
     * 初始化左侧侧边栏
     */
    initLeftSidebar() {
        const leftSidebarBtns = document.querySelectorAll('.left-sidebar .sidebar-btn');
        const { leftPanel } = this.elements;
        
        leftSidebarBtns.forEach(btn => {
            btn.addEventListener('click', () => {
                const target = btn.getAttribute('data-target');
                const wasActive = btn.classList.contains('active');
                
                // 切换按钮激活状态
                leftSidebarBtns.forEach(b => b.classList.remove('active'));
                
                // 切换面板显示
                const panels = document.querySelectorAll('.left-panel .panel-content');
                panels.forEach(panel => panel.classList.remove('active'));
                
                // 如果按钮之前是激活状态，则折叠面板，否则展开对应面板
                if (wasActive) {
                    leftPanel.classList.remove('expanded');
                } else {
                    btn.classList.add('active');
                    document.getElementById(`${target}-panel`).classList.add('active');
                    leftPanel.classList.add('expanded');
                }
            });
        });
    }
    
    /**
     * 初始化右侧侧边栏
     */
    initRightSidebar() {
        const rightSidebarBtns = document.querySelectorAll('.right-sidebar .sidebar-btn');
        const { rightPanel, projectContainer } = this.elements;
        
        rightSidebarBtns.forEach(btn => {
            btn.addEventListener('click', () => {
                const target = btn.getAttribute('data-target');
                const wasActive = btn.classList.contains('active');
                
                // 切换按钮激活状态
                rightSidebarBtns.forEach(b => b.classList.remove('active'));
                
                // 切换面板显示
                const panels = document.querySelectorAll('.right-panel .panel-content');
                panels.forEach(panel => panel.classList.remove('active'));
                
                // 如果按钮之前是激活状态，则折叠面板，否则展开对应面板
                if (wasActive) {
                    rightPanel.classList.remove('expanded');
                    projectContainer.classList.add('right-collapsed');
                } else {
                    btn.classList.add('active');
                    document.getElementById(`${target}-panel`).classList.add('active');
                    rightPanel.classList.add('expanded');
                    projectContainer.classList.remove('right-collapsed');
                }
            });
        });
        
        // 初始化时确保右侧面板展开状态与类名一致
        if (rightPanel.classList.contains('expanded')) {
            projectContainer.classList.remove('right-collapsed');
        } else {
            projectContainer.classList.add('right-collapsed');
        }
    }
    
    /**
     * 初始化AI助手功能
     */
    initAIAssistant() {
        const { aiInput, aiChat } = this.elements;
        
        if (aiInput && aiChat) {
            // 创建AI助手实例
            this.aiAssistant = new AIAssistant({
                inputElement: aiInput,
                chatElement: aiChat,
                onMessageSent: (message) => {
                    console.log('用户发送消息:', message);
                },
                onMessageReceived: (message) => {
                    console.log('AI回复消息:', message);
                }
            });
            
            // 初始化AI助手
            this.aiAssistant.init();
        }
    }
    


}

// 创建全局实例
let projectPageInstance = null;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    projectPageInstance = new ProjectPage();
});

// 导出类供其他模块使用
if (typeof module !== 'undefined' && module.exports) {
    module.exports = ProjectPage;
}